package com.xy.iot.netty.handle;

import cn.hutool.core.util.ObjectUtil;
import com.xy.iot.common.enums.DeviceHandleEnum;
import com.xy.iot.common.result.ChannelClientEventData;
import com.xy.iot.common.utils.IpUtil;
import com.xy.iot.common.utils.SpringContextUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

@Slf4j
public class ExceptionClientHandler extends ChannelDuplexHandler {



    /**
     * 处理业务异常次数
     */
    private int exception;

    public ExceptionClientHandler(){

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        exception++;
        Channel channel = ctx.channel();
        if(!ObjectUtil.isEmpty(channel.remoteAddress())){
            String address = IpUtil.getAddress(channel.remoteAddress());
            ChannelClientEventData connectServerData = new ChannelClientEventData(this, DeviceHandleEnum.ABNORMAL.getKey(), address, exception);
            if(!ObjectUtil.isEmpty(connectServerData) && !ObjectUtil.isEmpty(applicationContext)){
                applicationContext.publishEvent(connectServerData);
            }
            //由Tail节点对异常进行统一处理
            if(cause instanceof RuntimeException){
                log.info("处理业务异常："+channel.remoteAddress());
            }
            super.exceptionCaught(ctx, cause);
        }
    }
}
